package com.china.api.wechat.processor.main;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * request的helper类，主要是为解析xml提供便利方法
 * 
 * @author Ben
 * 
 */
public class Request {
	
	private static final XPathFactory xFactory = XPathFactory.newInstance();

	private static DocumentBuilder builder;
	static {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		try {
			builder = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

	}

	private final Document doc;

	public Request(String xml) throws SAXException, IOException {
		doc = builder.parse(new InputSource(new StringReader(xml)));
	}

	/**
	 * 根据xpath返回结点的值
	 * 
	 * @param xpath
	 * @return
	 * @throws SAXException
	 * @throws IOException
	 * @throws XPathExpressionException
	 */
	public String getValueByXPath(String xpath) throws SAXException,
			IOException, XPathExpressionException {
		XPathExpression expr = null;
		XPath path = xFactory.newXPath();
		expr = path.compile(xpath);
		Object content = expr.evaluate(doc, XPathConstants.STRING);
		return content.toString();
	}

}
